package com.cc.demo;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

//查询索引中的所有数据
public class Client {
    public static  void main(String[] args) throws IOException {
        //创建java和es的链接
        HttpHost httpHost = new HttpHost("127.0.0.1", 9200, "http");
        RestClientBuilder builder = RestClient.builder(httpHost);
        RestHighLevelClient client = new RestHighLevelClient(builder);
        System.out.println(client.indices());

        //编写查询操作
        //1、指定索引库
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("good");
        //2、构建查询条件
        SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        //3、建立查询条件的关系
        searchRequest.source(query);
        //4、发送请求
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        //5、展示响应结果
        SearchHits hits = response.getHits();
        System.out.println("took:"+response.getTook());
        System.out.println("timeout:"+response.isTimedOut());
        System.out.println("total:"+hits.getTotalHits());
        System.out.println("MaxScore:"+hits.getMaxScore());
        System.out.println("hits==================>>");
        for (SearchHit hit : hits){
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
        System.out.println("<============");


        //关闭连接
        client.close();
    }
}
